


ROOT_DIR := ../../../../
BUILD_DIR := build

ifndef PROJECT_NAME
# PROJECT_NAME := $(notdir $(shell pwd))
PROJECT_NAME := $(BUILD_DIR)/program
endif


USER_OBJS := 
C_SRCS :=
SECONDARY_FLASH := ../../firmware/code.bin 
SECONDARY_LIST := $(PROJECT_NAME).lst
SECONDARY_SIZE := $(PROJECT_NAME).map

CC_PREFIX := riscv-none-embed-
CC = gcc
AS = gcc
LD = g++
OD = objdump
OC = objcopy
SIZE = size


OBJS := 

LIBS := -lstartup -lnmsis -lm

C_FLAGS := -march=rv32imafc -mabi=ilp32f -mcmodel=medlow -msmall-data-limit=8 -msave-restore -mfdiv -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -fno-delete-null-pointer-checks -fno-unroll-loops  -g -std=gnu11 -MMD -MP
S_FLAGS := -march=rv32imafc -mabi=ilp32f -mcmodel=medlow -msmall-data-limit=8 -msave-restore -mfdiv -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -fno-delete-null-pointer-checks -fno-unroll-loops  -g -x assembler-with-cpp -MMD -MP
LD_FLAGS := -march=rv32imafc -mabi=ilp32f -mcmodel=medlow -msmall-data-limit=8 -msave-restore -mfdiv -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -fno-delete-null-pointer-checks -fno-unroll-loops  -g -T "../../src/ci112x.lds" -nostartfiles -Xlinker --gc-sections -Wl,-Map,"$(PROJECT_NAME).map" --specs=nano.specs


LD_FLAGS += -L$(ROOT_DIR)/libs

all: $(PROJECT_NAME).elf secondary-outputs

include $(BUILD_DIR)/source_file.mk

$(PROJECT_NAME).elf: $(OBJS) $(USER_OBJS)
	@echo 'Building target: $@'
	@echo 'Invoking: GNU RISC-V Cross C++ Linker'
	$(CC_PREFIX)$(LD) $(LD_FLAGS) -o "$(PROJECT_NAME).elf" $(OBJS) $(USER_OBJS) $(LIBS) 
	@echo 'Finished building target: $@'
	@echo ' '
	echo $(PROJECT_NAME)
	echo $(shell pwd)

$(SECONDARY_FLASH): $(PROJECT_NAME).elf
	@echo 'Invoking: GNU RISC-V Cross Create Flash Image'
	mkdir -p ../../firmware/user_code && $(CC_PREFIX)$(OC) -O binary "$(PROJECT_NAME).elf"  $(SECONDARY_FLASH)
	@echo 'Finished building: $@'
	@echo ' '

$(PROJECT_NAME).lst: $(PROJECT_NAME).elf
	@echo 'Invoking: GNU RISC-V Cross Create Listing'
	$(CC_PREFIX)$(OD) --demangle --disassemble --reloc --wide "$(PROJECT_NAME).elf" > "$(PROJECT_NAME).lst"
	@echo 'Finished building: $@'
	@echo ' '

$(PROJECT_NAME).map: $(PROJECT_NAME).elf
	@echo 'Invoking: GNU RISC-V Cross Print Size'
	$(CC_PREFIX)$(SIZE) --format=berkeley "$(PROJECT_NAME).elf"
	@echo 'Finished building: $@'
	@echo ' '	

%.o : %.c
	$(CC_PREFIX)$(CC) $(C_FLAGS) -c -o "$@" "$<"

%.o : %.S
	$(CC_PREFIX)$(AS) $(S_FLAGS) -c -o "$@" "$<"

clean:
	-$(RM) $(CC_DEPS) $(C++_DEPS) $(OBJS) $(C_UPPER_DEPS) $(CXX_DEPS) $(SECONDARY_FLASH) $(SECONDARY_LIST) $(SECONDARY_SIZE) $(ASM_DEPS) $(S_UPPER_DEPS) $(C_DEPS) $(CPP_DEPS) $(PROJECT_NAME).elf
	-@echo ' '

secondary-outputs: $(SECONDARY_FLASH) $(SECONDARY_LIST) $(SECONDARY_SIZE)

.PHONY: all clean dependents
